package com.markerhub.shiro;

import cn.hutool.json.JSONUtil;
import com.markerhub.common.lang.Result;
import com.markerhub.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt过滤器
 * 用来创建token和做一些请求处理
 * 过滤器继承AuthenticatingFilter并重写方法
 * 还有一个常用的是BaseHttp...啥的过滤器，区别是这个封装的更彻底点
 *
 * JwtFilter逻辑
 * 访问接口通过JwtFilter
 * 无token直接访问接口判断权限以后返回结果
 * 有token通过siro校验token以后再访问接口并进行权限判断
 */
@Component
public class JwtFilter extends AuthenticatingFilter{
    @Autowired
    JwtUtils jwtUtils;
    /**(通过token创建自定义的JwtToken)
     * 强制转换为HttpServletRequest
     * 判断Header中的token是否为空
     * 为空返回空，不为空调用shiro方法去调用shiro的execute.login()创建jwt token
     * 之后把token给Realm处理
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        String jwt=request.getHeader("Authorization");
        if(StringUtils.isEmpty(jwt)){
            return null;
        }
        return new JwtToken(jwt);
    }

    /**
     * 生成jwt token以后会判断token是否过期等
     * token为空或者token过期就返回true表示拒绝连接
     * 有token先校验然后判断是否放通
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        String jwt=request.getHeader("Authorization");
        if(StringUtils.isEmpty(jwt)){
            return true;
        }else {
            Claims claim = jwtUtils.getClaimByToken(jwt);
            if(claim==null||jwtUtils.isTokenExpired(claim.getExpiration())){
                //校验token步骤 空或者过期抛出异常
                throw new ExpiredCredentialsException("token失效");
            }
            //token有效就传递请求执行登录操作(login最后会交给realm处理)出现异常时会捕获，最好重写onLoginFailure方法
            return executeLogin(servletRequest,servletResponse);

        }
    }

    /**
     * 前面一个方法执行executeLogin方法如果出现错误会调用onLoginFailure方法
     * 先判断错误原因，把抛出的错误封装后返回前端response.getWriter.print();
     * 返回false
     * @param token
     * @param e
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpServletResponse= (HttpServletResponse) response;
        Throwable throwable=e.getCause()==null?e:e.getCause();
        Result result = Result.fail(throwable.getMessage());
        //结果以json形式返回 hutool工具可以转换
        String json = JSONUtil.toJsonStr(result);
        try {
            response.getWriter().print(json);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return false;

    }

    /**
     * 过滤器在controller之前也要配置跨域
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        // 跨域时会首先发送一个OPTIONS请求，这里我们给OPTIONS请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }

        return super.preHandle(request, response);
    }

}
